/**
 * 
 */
package jvs.vfs.util.note;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import x.java.io.File;
import x.java.io.FileReader;

/**
 * @author qiangli
 *
 */
public class NoteIterator  implements Iterator<Object> {
	private Note note;
	private FileReader fr;
	private BufferedReader br;
	private String crlf;
	private boolean inited;
	public NoteIterator(String path, String crlf) throws IOException {
		try {
			File cf = NoteHelper.getNoteFile(path);
			this.fr = new FileReader(cf);
			this.br = new BufferedReader(fr, File.BUFSIZE);
			this.note = new Note();
			this.crlf = crlf;
			inited = true;
		} catch (FileNotFoundException e) {
			inited = false;
			//e.printStackTrace();
		} catch (IOException e) {
			inited = false;
			throw e;
		}
	}

	public boolean hasNext() {
		if (!inited) {
			return false;
		}
		try {
			String line = br.readLine();
			if (line == null) {
				cleanup();
				return false;
			}
			note.date = NoteHelper.parseDate(line); //date
			note.author = br.readLine(); //author
			note.name = br.readLine(); //name
			if (note.author == null || note.name == null) {
				cleanup();
				return false;
			}
			StringBuilder sb = new StringBuilder(); //body
			while ((line = br.readLine()) != null) {
				if (NoteHelper.isEmpty(line)) {
					break;
				}
				sb.append(line);
				sb.append(crlf);
			}
			note.body = sb.toString();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		cleanup();
		return false;
	}

	public Note next() {
		return note;
	}

	public void remove() {
		throw new RuntimeException("Not supported");
	}
	
	private void cleanup() {
		try {
			fr.close();
			br.close();
			note = null;
		} catch (Exception e) {
			e.printStackTrace();
		}	
		inited = false;
	}
}
